// const { HttpException } = require('../core/http-exception');

const { HttpException } = require('../core/http-exception');

// 全局的处理异常中间件
const catchError = async (ctx, next) => {
  try {
    await next();
  } catch (error) {
    // 判断已知异常还是未知异常
    // 已知异常有一个明显的特点,有自定义的errorCode
    // if (error.errorCode) {
    if (error instanceof HttpException) {
      ctx.body = {
        msg: error.msg,
        error_code: error.errorCode,
        request: `${ctx.method} ${ctx.path}`
      };
      ctx.status = error.statusCode;
    }
  }
};

module.exports = catchError;